import json
import time
import requests
from src.signer import Signer
from src.config_util import load_config


class CustomsAPI:
    def __init__(self):
        self.config = load_config()
        self.customs179_url = self.config.get('api', 'customs179_url')
        self.check_url = self.config.get('api', 'check_url')
        self.back_url = self.config.get('api', 'back_url')
        self.cert_no = self.config.get('account', 'cert_no')

    def send_179_data(self, sign, data_str):
        # 去看179数据上报接口文档
        # 完成请求后，成功后要调用调用回调接口回调到商户平台后端
        sign_array = data_str.split("||")
        pay_ex_info_str = "{"
        for sign_item in sign_array:
            if sign_item.startswith('"payExchangeInfoHead'):
                item_data = sign_item.split('"payExchangeInfoHead":"')[1]
                pay_ex_info_str += '"payExchangeInfoHead":' + item_data[:-1] + ','
            elif sign_item.startswith('"payExchangeInfoLists'):
                item_data = sign_item.split('"payExchangeInfoLists":"')[1]
                pay_ex_info_str += '"payExchangeInfoLists":' + item_data[:-1]+ ','
            else:
                pay_ex_info_str += sign_item + ','
        pay_ex_info_str += f'"certNo":"{self.cert_no}",' + f'"signValue":"{sign}"'+'}'
        body = {
            "payExInfoStr": pay_ex_info_str
        }
        result = requests.post(self.customs179_url, data=body, headers={
            "Content-Type": "application/x-www-form-urlencoded"
        }, verify=False)
        return result.json()

    def get_chek_data(self):
        headers = {
         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
        }
        result = requests.post(self.check_url, headers=headers, verify=False)
        return result.json()

    def check_success_callback(self, orderno, status='success', request_num=1):
        if request_num <= 5:
            now_time = str(int(time.time() * 1000))
            body = {
                "orderNo": orderno,
                "status": status,
                "message": "上报成功" if status == 'success' else '上报失败',
                "reportTime": now_time,
            }
            headers = {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
                "Content-Type": "application/json"
            }
            result = requests.post(self.back_url, json=body, headers=headers, verify=False)
            if result.status_code != 200:
                time.sleep(3)
                self.check_success_callback(orderno, status, request_num + 1)

    def get_check_sign_str(self,time_str, data_json=None):
        if not data_json:
            data_json = self.get_chek_data()
        data_str = None
        if data_json and data_json != {}:
            data_str = (f'"sessionID":"{data_json.get("sessionID")}"||'
                        + f'"payExchangeInfoHead":"{json.dumps(data_json.get("payExchangeInfoHead"), ensure_ascii=False, separators=(',', ':'), allow_nan=False)}"||'
                        + f'"payExchangeInfoLists":"{json.dumps(data_json.get("payExchangeInfoLists"), ensure_ascii=False, separators=(',', ':'), allow_nan=False)}"||'
                        + f'"serviceTime":"{time_str}"')
        return data_str

    def get_check_data_sign(self, time_str, sign_data_str=None):
        if not sign_data_str:
            sign_data_str = self.get_check_sign_str(time_str)
        sign_api = Signer()
        sign = sign_api.sign(sign_data_str)
        return sign

def main():
    api = CustomsAPI()
    api.check_success_callback('8250904134228532600004')
    # check_data = api.get_chek_data()
    # if check_data and check_data != {}:
    #     code = "CUSTOMS" + api.check_url.split('check')[-1]
    #     session_id = code + str(int(time.time() * 1000))
    #     check_data['sessionID'] = session_id
    #     now_time = str(int(time.time() * 1000))
    #     check_sign_str = api.get_check_sign_str(now_time, check_data)
    #     sign = api.get_check_data_sign(now_time, check_sign_str)
    #     customs179_result = api.send_179_data(sign, check_sign_str, now_time)
    #     print(customs179_result)
    #     if customs179_result.get('code') == "10000":
    #         api.check_success_callback(check_data.get('payExchangeInfoLists')[0].get('orderNo'))


if __name__ == "__main__":
    main()